package mc.support.task.mgr;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yun    <br/>
 * Date: 2014-05-01  <br/>
 */
public class MsgChan<T> {

    private static final int DEFAULT_QUEUE_COUNT_IN_GROUP = 5;
    private static final int DEFAULT_QUEUE_CAP = 100;
    private byte[] shared = new byte[0];

    private Map<String, QueueGroup<T>> queueGroups = new HashMap<String, QueueGroup<T>>();

    public QueueGroup<T> getQueueGroup( String address, final int queueCount, final int queueCap ) {
        QueueGroup<T> qg = queueGroups.get( address );
        if ( null == qg ) {
            synchronized ( shared ) {
                qg = queueGroups.get( address );
                if ( null == qg ) {
                    qg = new QueueGroup<T>( queueCount, queueCap );
                    queueGroups.put( address, qg );
                }
            }
        }
        return qg;
    }

    public void initQueueCap( String address, final int queueCount, final int queueCap ) {
        getQueueGroup( address, queueCount, queueCap );
    }

    public QueueGroup<T> getQueueGroup(String address) {
        return getQueueGroup( address, DEFAULT_QUEUE_COUNT_IN_GROUP, DEFAULT_QUEUE_CAP );
    }

    public T receive(String address) throws InterruptedException {
        return getQueueGroup( address ).take();
    }

    public T tryReceive(String address) {
        return getQueueGroup( address ).poll();
    }

    public void send(String address, T t) throws InterruptedException {
        getQueueGroup( address ).put( t );
    }

    public boolean trySend(String address, T t) {
        return getQueueGroup( address ).offer( t );
    }

}
